<!-- 文章列表 -->
<template>
  <div class="DealerInfoStyle">
    <div class="cardAdmin">
      <div class="formContainer">
        <div class="formSearch">
          <span class="mhmz">日文标题：</span>
          <el-input style="flex: 3" v-model="form.title_ja"></el-input>
        </div>
        <div class="formSearch">
          <span class="mhmz">韩文标题：</span>
          <el-input style="flex: 3" v-model="form.title_ko"></el-input>
        </div>
        <div class="formSearch">
          <span class="mhmz">英文标题：</span>
          <el-input style="flex: 3" v-model="form.title_en"></el-input>
        </div>
        <div class="formSearch">
          <span class="mhmz">简体标题：</span>
          <el-input style="flex: 3" v-model="form.title_zh_cn"></el-input>
        </div>
        <div class="formSearch">
          <span class="mhmz">繁体标题：</span>
          <el-input style="flex: 3" v-model="form.title_zh_tw"></el-input>
        </div>
        <div class="qpwo">
          <el-button class="el-icon-refresh" type="info" size="small" @click="resetForm()">
            重置</el-button>
          <el-button class="el-icon-search" type="primary" size="small" @click="get_listOfResearchReports()">
            查询</el-button>
        </div>
        <div style="position: absolute; left: 10px; bottom: 5px">
          <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="addbtn()">新增文章</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="CompanyTable" v-loading="table_loading" border size="small"
      style="width: 100%; min-height: 78%; max-height: 78%; overflow: auto">
      <el-table-column resizable prop="research_report_id" label="id" width="60" align="center">
      </el-table-column>
      <el-table-column resizable prop="sort" label="序号" width="auto" min-width="60px" align="center">
      </el-table-column>
      <el-table-column resizable prop="heating" label="热点级别" width="auto" min-width="70px" align="center">
      </el-table-column>
      <el-table-column resizable prop="category_name_zh_tw" label="行业" width="auto" min-width="120px" align="center">
      </el-table-column>

      <el-table-column resizable prop="is_navi_menu" label="是否加入导航" width="auto" min-width="120px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.is_navi_menu == 1 ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column resizable prop="status" label="是否启用" width="auto" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 1 ? "已启用" : "未启用" }}</span>
        </template>
      </el-table-column>
      <el-table-column resizable prop="is_public" label="是否公开" width="auto" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.is_public == 0 ? "公开" : "不公开" }}</span>
        </template>
      </el-table-column>


    <!-- <el-table-column resizable prop="category_id" label="行业" width="auto" min-width="100px" align="center">
                                                                            </el-table-column> -->
    <!-- <el-table-column resizable prop="stock_code" label="关联的股票代码" width="auto" min-width="200px" align="center">
                                                                                  </el-table-column> -->
    <!-- <el-table-column resizable prop="title_zh_cn" label="标题（简体中文）" width="auto" min-width="200px" align="center">
                                                                                  </el-table-column> -->

      <el-table-column resizable prop="title_zh_tw" label="标题（繁体中文）" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="subtitle_zh_tw" label="副标题（繁体中文）" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="img_max_zh_tw" label="大图（繁体中文）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_max_zh_tw" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_max_zh_tw]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_max_zh_tw == ""
                  ? "加载失败"
                  : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="img_min_zh_tw" label="缩略图（繁体中文）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_min_zh_tw" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_min_zh_tw]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_min_zh_tw == ""
                  ? "加载失败"
                  : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
    <!-- <el-table-column resizable prop="title_en" label="标题（英语）" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="title_ja" label="标题（日语）" width="auto" min-width="200px" align="center">
      </el-table-column>
      <el-table-column resizable prop="title_ko" label="标题（韩语）" width="auto" min-width="200px" align="center">
                                                                                  </el-table-column> -->
    <!-- <el-table-column resizable prop="img_max_en" label="大图（英语）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_max_en" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_max_en]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_max_en == "" ? "加载失败" : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="img_max_ja" label="大图（日语）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_max_ja" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_max_ja]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_max_ja == "" ? "加载失败" : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="img_max_ko" label="大图（韩语）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_max_ko" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_max_ko]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_max_ko == "" ? "加载失败" : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
    
      <el-table-column resizable prop="img_min_en" label="缩略图（英语）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_min_en" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_min_en]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_min_en == "" ? "加载失败" : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="img_min_ja" label="缩略图（日语）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_min_ja" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_min_ja]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_min_ja == "" ? "加载失败" : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column resizable prop="img_min_ko" label="缩略图（韩语）" width="auto" min-width="180px" align="center">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 20px" :src="'' + scope.row.img_min_ko" :fit="roleHeadgear"
            :preview-src-list="['' + scope.row.img_min_ko]">
            <div slot="error" class="image-slot" style="width: 50px">
              <div style="width: 50px">
                {{
                  scope.row.img_min_ko == "" ? "加载失败" : "空图片或者地址错误"
                }}
              </div>
            </div>
          </el-image>
        </template>
            </el-table-column> -->
      <el-table-column resizable label="操作" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button @click="tableEditing(scope.row)" type="primary" plain size="small">编辑</el-button>
          <el-button @click="del_deleteResearchReport(scope.row.research_report_id)" type="danger" plain
            size="small">刪除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="text-align: right; margin-top: 5px">
      <el-pagination background layout="prev, pager, next,total" :total="total" :page-size="pagesize"
        @current-change="current_change"></el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="titles" :visible.sync="dialogVisible" width="70%"
      @close="handleClose" top="1vh">
      <div class="pop-up-form">
        <div class="ttyyuu">
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">选择语言：</span>
            <el-select disabled style="flex: 6" v-model="selectedLanguage" placeholder="选择语言" @change="handleLanguageChange">
              <el-option v-for="item in languages" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div style="display: flex; flex: 1">
            <span class="bbnnmm">是否启用：</span>
            <el-switch style="flex: 6; height: 40px; width: 100%" v-model="addform.status" active-text="是"
              :active-value="1" :inactive-value="0" inactive-text="否"></el-switch>
          </div>
          <div style="display: flex; flex: 1">
            <span class="bbnnmm">是否公开：</span>
            <el-switch style="flex: 6; height: 40px; width: 100%" v-model="addform.is_public" active-text="是"
              :active-value="0" :inactive-value="1" inactive-text="否"></el-switch>
          </div>
        </div>
        <div class="ttyyuu">
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">标题：</span>
            <el-input style="flex: 6" v-model="addform.title"></el-input>
          </div>
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">股票代码：</span>
            <el-input style="flex: 6" v-model="addform.stock_code"></el-input>
          </div>
          <div style="display: flex; flex: 1">
            <span class="bbnnmm">添加时间：</span>
            <el-date-picker style="flex: 6" v-model="addform.add_time" type="datetime" placeholder="请选择添加时间"
              :format="'yyyy-MM-dd HH:mm:ss'" :value-format="'yyyy-MM-dd HH:mm:ss'">
            </el-date-picker>
          </div>
        </div>

        <div class="ttyyuu">
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">行业：</span>
          <!-- <el-cascader clearable style="flex: 11" :options="[hangyedata]" :props="{
              value: 'category_id',
              label: 'category_name_zh_tw',
              children: 'childs',
                                                  }" placeholder="请选择" @change="handleChange22" :show-all-levels="false" /> -->
            <el-select v-model="addform.category_id" placeholder="请选择" clearable style="flex: 11">
              <el-option v-for="item in hangyedata" :key="item.category_id" :label="item.category_name_zh_tw"
                :value="item.category_id" />
            </el-select>
          </div>
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">简介：</span>
            <el-input style="flex: 11" v-model="addform.introduction"></el-input>
          </div>
        </div>
        <div class="ttyyuu">
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">加热：</span>
            <el-select style="flex: 11" v-model="addform.heating" placeholder="请选择加热等级" @change="handleChange">
              <el-option label="不加热" :value="0" />
              <el-option label="1级加热" :value="1" />
              <el-option label="2级加热" :value="2" />
            </el-select>
          </div>
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">副标题：</span>
            <el-input style="flex: 11" v-model="addform.subtitle"></el-input>
          </div>
        </div>
        <div class="ttyyuu">
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">序号：</span>
            <el-input style="flex: 11" v-model="addform.sort"></el-input>
          </div>
          <div style="flex: 1; display: flex">
            <span class="bbnnmm">是否加入导航：</span>
            <el-select v-model="addform.is_navi_menu" placeholder="请选择" style="flex: 11">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </div>
        </div>




        <div class="ttyyuu">
          <div style="flex: 1; display: flex; align-items: center">
            <span class="bbnnmm">缩略图：</span>
            <div style="flex: 6; padding: 0 15px">
              <img :src="thumbnailPreview" alt="缩略图" class="rtrtqw" @click="triggerFileInput('fileInput1')" />
              <input type="file" ref="fileInput1" id="fileInput1" accept="image/*" style="display: none"
                @change="handleFileChange1" />
              <div v-if="imageUrl" class="fgfgas"></div>
              <!-- 选择文件后显示裁剪框 -->
              <div v-if="imageUrl" class="cvcvax">
                <img :src="imageUrl" ref="imagezz" alt="Image to crop" style="max-width: 100%" />
                <!-- 裁剪按钮 -->
                <button class="btncaijian" @click="cropImage('1')">裁剪</button>
              </div>
            </div>
          </div>

          <div class="qqaazz">
            <span class="bbnnmm">大图：</span>
            <div style="flex: 6; padding: 0 15px">
              <img :src="largeImagePreview" alt="大图" class="rtrtqw" @click="triggerFileInput('fileInput2')" />
              <input type="file" ref="fileInput2" id="fileInput2" accept="image/*" style="display: none"
                @change="handleFileChange2" />
              <div v-if="imageUrlt" class="fgfgas"></div>
              <!-- 选择文件后显示裁剪框 -->
              <div v-if="imageUrlt" class="cvcvax">
                <img :src="imageUrlt" ref="imagexx" alt="Image to crop" style="max-width: 100%" />
                <!-- 裁剪按钮 -->
                <button class="btncaijian" @click="cropImage('2')">裁剪</button>
              </div>
            </div>
          </div>
        </div>

        <div class="pop-up-form" style="min-height: calc(100vh - 200px - 5vh - 54px - 120px - 40px)">
          <div style="width: 100%; padding: 0 0 0 4%">
            <h3 class="wweerr">
              内容：
            </h3>
            <div style="border: 1px solid #ccc; height: auto">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor class="aassdd" v-model="html" :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated"
                @onChange="onChange" @onDestroyed="onDestroyed" @onMaxLength="onMaxLength" @onFocus="onFocus"
                @onBlur="onBlur" @customAlert="customAlert" @customPaste="customPaste" />
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button v-show="titles == '新增'" :loading="btnstate" type="primary" @click="add_newResearchReportAdded()"
          size="small">确
          定</el-button>
        <el-button v-show="titles == '编辑'" :loading="btnstate" type="primary" @click="upd_researchReportEditor()"
          size="small">更 新</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  listOfResearchReports,
  newResearchReportAdded,
  researchReportEditor,
  deleteResearchReport,
  singleColumnContent,
  industryContent,
  uploadImage,
} from "@/utils/api";
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.min.css";
export default {
  name: "CompanyInfo",
  components: { Editor, Toolbar },
  data() {
    return {
      table_loading: false,
      btnstate: false,
      cropper: null, // cropper 实例
      imageLink: "https://www.google.com/",
      // 富文本
      editor: null, // 富文本实例对象
      html: "", // 富文本初始html
      toolbarConfig: {
        excludeKeys: [
          // 'group-image',
          "group-video",
        ],
      },
      isVisible: false,
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          // 配置图片上传
          uploadImage: {
            server: "/admin/System/imgUpload", // 上传图片的地址
            fieldName: "image", // 后端接收图片的字段名
            maxFileSize: 2 * 1024 * 1024, // 图片大小限制，单位 byte
            maxNumberOfFiles: 5, // 最多可上传图片数
            headers: {
              token: localStorage.getItem("token"), // 将 token 添加在请求头中
            },
            allowedFileTypes: ["image/*"], // 限制文件类型
            onSuccess(file, res) {
              // 自定义处理上传成功后的逻辑
              console.log("图片上传成功", res, file);
            },
            onFailed(file, res) {
              console.log(res, file, "失败");
              // 自定义处理上传失败后的逻辑
              // console.error('图片上传失败', res);
            },
            // 自定义上传逻辑
            customInsert: (res, insertFn) => {
              const imageUrl = "" + res.data[0];

              insertFn(imageUrl);
            },
          },
        },
      }, // 富文本提示
      mode: "default", // or 'simple'
      form: {
        title_ja: "",
        title_ko: "",
        title_en: "",
        title_zh_tw: "",
        title_zh_cn: "",
      },
      selectedLanguage: "content_text_zh_tw", // 当前选择的语言
      addform: {
        status: 0,
        body_html: "",
        title: "",
        add_time: "",
        stock_code: "",
        is_public: 0,
        heating: 0,
        category_id: "",
        subtitle: "",
        introduction: "",
        sort: "",
        is_navi_menu: 0
      },
      imageUrl: null,
      imageUrlt: null,
      CompanyTable: [],
      languages: [
        { value: "content_text_en", label: "英语" },
        { value: "content_text_ja", label: "日语" },
        { value: "content_text_ko", label: "韩语" },
        { value: "content_text_zh_tw", label: "繁体中文" },
        { value: "content_text_zh_cn", label: "简体中文" },
      ],
      dialogVisible: false,
      total: 100, //总条数
      pagesize: 10, //指定展示多少条
      currentPage: 1, //当前页码
      titles: "",
      roleHeadgear: null,
      dangeColumn: [],
      row: {},
      roleHeadgear1: "",
      roleHeadgear2: "",
      hangyedata: [],
      thumbnailPreview: require("@/assets/sctpmr.jpg"), // 缩略图预览URL
      largeImagePreview: require("@/assets/sctpmr.jpg"), // 大图预览URL
      selectedValue: [], // 选中的值
    };
  },
  mounted() {
    this.get_listOfResearchReports();
    this.get_industryContent();
  },

  methods: {
    triggerFileInput(refName) {
      this.$refs[refName].click(); // 触发文件选择
    },
    handleChange(value) {
      console.log(this.addform.category_id, 'this.addform.category_id');
      console.log("Selected Value:", value); // 打印选中值
    },
    handleChange22(valueArr) {
      this.addform.category_id = valueArr?.length ? valueArr[valueArr.length - 1] : null
    },

    async shangchuan(roleHeadgear, type) {
      const formData = new FormData();
      formData.append("image", roleHeadgear); // 添加文件
      formData.append("position", "index"); // 添加position字段
      const response = await uploadImage(formData); // 调用上传接口

      if (type == "1") {
        this.thumbnailPreview =
          "" + response.data.data[0]; // 更新img1的预览地址
        this.roleHeadgear1 = response.data.data[0];
        this.$message.info(response.data.msg);
      } else {
        this.largeImagePreview =
          "" + response.data.data[0]; // 更新img2的预览地址
        this.roleHeadgear2 = response.data.data[0];
        this.$message.info(response.data.msg);
      }
    },
    // 裁剪图片
    cropImage(type) {
      if (this.cropper) {
        // 获取裁剪后的 Canvas
        const canvas = this.cropper.getCroppedCanvas();

        // 将 Canvas 转换为 Blob 格式，指定图片类型
        canvas.toBlob(
          (blob) => {
            const timestamp = Date.now(); // 获取当前时间戳
            // 如果裁剪完成，创建一个新的 File 对象
            let roleHeadgear =
              type == "1" ? this.roleHeadgear1 : this.roleHeadgear2;
            roleHeadgear = new File([blob], `${timestamp}.jpeg`, {
              type: blob.type,
            });
            this.$nextTick(() => {
              this.shangchuan(roleHeadgear, type);
              console.log(
                `裁剪后的文件大小: ${(
                  roleHeadgear.size /
                  (1024 * 1024)
                ).toFixed(2)}MB`
              );
            });

            // 销毁 cropper 实例
            this.imageUrl = null;
            this.imageUrlt = null;
            this.cropper.destroy();
            this.cropper = null;
            if (type == "1") this.thumbnailPreview = null;
            if (type == "2") this.largeImagePreview = null;
          },
          "image/jpeg",
          0.98
        ); // 你可以根据需要设置为 'image/png' 或其他格式
      }
    },
    async handleFileChange1(event) {
      if (event.target.files[0]) {
        // 初始化裁剪框
        this.roleHeadgear1 = event.target.files[0];
        this.imageUrl = URL.createObjectURL(this.roleHeadgear1);
        this.$nextTick(() => {
          console.log(this.$refs, "this.$refs.image");
          const imageElement = this.$refs.imagezz;
          if (this.cropper) {
            this.cropper.destroy(); // 如果有旧的 cropper 实例，销毁
          }
          this.cropper = new Cropper(imageElement, {
            aspectRatio: 2 / 1, // 保持裁剪框为 1.75:1 比例
            viewMode: 1, // 裁剪框模式
            autoCropArea: 0.8, // 默认裁剪区域占比
            responsive: true, // 响应式
          });
        });
        this.$message.success("上传成功");
      }
    },
    async handleFileChange2(event) {
      if (event.target.files[0]) {
        // 初始化裁剪框
        this.roleHeadgear2 = event.target.files[0];
        this.imageUrlt = URL.createObjectURL(this.roleHeadgear2);
        this.$nextTick(() => {
          console.log(this.$refs, "this.$refs.image");
          const imageElement = this.$refs.imagexx;
          if (this.cropper) {
            this.cropper.destroy(); // 如果有旧的 cropper 实例，销毁
          }
          this.cropper = new Cropper(imageElement, {
            aspectRatio: 2.1 / 1, // 保持裁剪框为 1.75:1 比例
            viewMode: 1, // 裁剪框模式
            autoCropArea: 0.8, // 默认裁剪区域占比
            responsive: true, // 响应式
          });
        });
        this.$message.success("上传成功");
      }
    },
    handleFileChange(event) {
      this.roleHeadgear = event.target.files[0];
      if (this.roleHeadgear) {
        this.$message.success("上传成功");
      }
    },
    // 处理数据
    filterData(data) {
      const allowedKeys = [
        "category_id",
        "category_level",
        "category_name_zh_tw",
        "parent_id",
      ];

      // 保留必要字段
      const filteredData = {};
      for (const key in data) {
        if (allowedKeys.includes(key)) {
          filteredData[key] = data[key];
        }
      }

      // 递归处理 childs
      if (data.childs && Array.isArray(data.childs)) {
        filteredData.childs = data.childs.map((child) =>
          this.filterData(child)
        );
      }

      return filteredData;
    },
    // 行业栏目查询
    async get_industryContent() {
      const res = await industryContent().catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        res.data.data.forEach((element) => {
          if (element.category_type == 2) {
            this.hangyedata = this.filterData(element).childs;
            console.log(this.hangyedata, 'this.hangyedata');
          }
        });
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 查询文章列表
    async get_listOfResearchReports(str) {
      this.table_loading = true
      let data = {};
      data.page = this.currentPage;

      if (this.form.title_ja !== "") {
        data.title_ja = this.form.title_ja;
      }
      if (this.form.title_ko !== "") {
        data.title_ko = this.form.title_ko;
      }
      if (this.form.title_en !== "") {
        data.title_en = this.form.title_en;
      }
      if (this.form.title_zh_tw !== "") {
        data.title_zh_tw = this.form.title_zh_tw;
      }
      if (this.form.title_zh_cn !== "") {
        data.title_zh_cn = this.form.title_zh_cn;
      }

      const res = await listOfResearchReports(data).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.table_loading = false
        this.$message.success(res.data.message);
        this.CompanyTable = res.data.data.data;
        this.total = res.data.data.total;
        if (str) this.btnstate = false
      } else {
        if (str) this.btnstate = false
        this.table_loading = false
        this.$message.error(res.data.message);
      }
    },
    // 新增文章
    async add_newResearchReportAdded() {
      this.btnstate = true
      let data = new FormData();

      // 检查语言是否已选择
      if (!this.selectedLanguage) {
        this.$message.info("请选择语言");
        this.btnstate = false
        return;
      }

      // 映射语言字段，减少冗余代码
      const languageMap = {
        content_text_ja: "ja",
        content_text_ko: "ko",
        content_text_en: "en",
        content_text_zh_tw: "zh_tw",
        content_text_zh_cn: "zh_cn",
      };

      // 获取语言后缀（例如：'ja'、'ko'、'en'、'zh_tw'）
      const langSuffix = languageMap[this.selectedLanguage];

      // 检查是否找到对应的语言后缀
      if (langSuffix) {
        // 拼装字段名并添加到 FormData
        data.append(`title_${langSuffix}`, this.addform.title);
        data.append(`subtitle_${langSuffix}`, this.addform.subtitle);
        data.append(`img_min_${langSuffix}`, this.roleHeadgear1);
        data.append(`img_max_${langSuffix}`, this.roleHeadgear2);
        data.append(this.selectedLanguage, this.editor.getHtml());
        if (this.addform.introduction) {
          data.append(`introduction_${langSuffix}`, this.addform.introduction);
        }
      } else {
        this.$message.info("语言字段不存在");
        this.btnstate = false
      }
      if (this.addform.sort || this.addform.sort == 0) {
        data.append("sort", this.addform.sort);
      }
      data.append("is_navi_menu", this.addform.is_navi_menu);

      data.append("is_public", this.addform.is_public);
      data.append("status", this.addform.status);
      data.append("add_time", this.addform.add_time);
      data.append("stock_code", this.addform.stock_code);
      data.append("heating", this.addform.heating);
      if (this.addform.category_id) {
        data.append("category_id", this.addform.category_id);
      } else {
        this.$message.warning('请填写行业')
        this.btnstate = false
        return
      }

      const res = await newResearchReportAdded(data).catch((err) => {
        this.btnstate = false
        console.log(err, 'errerrerr');
        this.$message.error(err.message)
        return console.error(err);
      });
      if (res && res.status == "200") {

        this.dialogVisible = false;
        this.$message.success(res.data.message);
        this.get_listOfResearchReports(true);
        this.roleHeadgear1 = "";
        this.roleHeadgear2 = "";
      } else {
        this.btnstate = false
        this.$message.error(res.data.message);
      }
    },
    // 查询单个文章
    async get_singleColumnContent(id) {
      let data = {};
      const res = await singleColumnContent(data, id).catch((err) => {
        return console.error(err);
      });
      if (res && res.status == "200") {
        this.$message.success(res.data.message);

        this.dangeColumn = res.data.data.data;
      } else {
        this.$message.error(res.data.message);
      }
    },
    // 更新文章
    async upd_researchReportEditor() {
      this.btnstate = true
      let data = new FormData();

      if (this.addform.status) {
        data.append("status", this.addform.status);
      }
      if (this.addform.sort || this.addform.sort == 0) {
        data.append("sort", this.addform.sort);
      }
      if (this.addform.is_public == 0 || this.addform.is_public == 1) {
        data.append("is_public", this.addform.is_public);
      }

      if (this.editor.getHtml()) {
        data.append(this.selectedLanguage, this.editor.getHtml());
      }

      if (this.addform.stock_code) {
        data.append("stock_code", this.addform.stock_code);
      }

      if (this.addform.id) {
        data.append("research_report_id", this.addform.id);
      }

      if (this.addform.heating || this.addform.heating == 0) {
        data.append("heating", this.addform.heating);
      }
      if (this.addform.category_id) {
        data.append("category_id", this.addform.category_id);
      }

      // 映射语言字段，减少冗余代码
      const languageMap = {
        content_text_ja: "ja",
        content_text_ko: "ko",
        content_text_en: "en",
        content_text_zh_tw: "zh_tw",
        content_text_zh_cn: "zh_cn",
      };
      data.append("is_navi_menu", this.addform.is_navi_menu);
      // 获取语言后缀（例如：'ja'、'ko'、'en'、'zh_tw'）
      const langSuffix = languageMap[this.selectedLanguage];

      // 检查是否找到对应的语言后缀
      if (langSuffix) {
        if (this.addform.title) {
          data.append(`title_${langSuffix}`, this.addform.title);
        }
        if (this.addform.introduction) {
          data.append(`introduction_${langSuffix}`, this.addform.introduction);
        }
        if (this.addform.subtitle) {
          data.append(`subtitle_${langSuffix}`, this.addform.subtitle);
        }
        if (this.roleHeadgear1) {
          data.append(`img_min_${langSuffix}`, this.roleHeadgear1);
        }
        if (this.roleHeadgear2) {
          data.append(`img_max_${langSuffix}`, this.roleHeadgear2);
        }
      } else {
        this.$message.info("语言字段不存在");
        this.btnstate = false
      }
      // let data = {
      //   status: this.addform.status,
      //   [this.selectedLanguage]: this.editor.getHtml() // 使用计算属性名
      // }

      const res = await researchReportEditor(data, this.addform.id).catch(
        (err) => {
          this.btnstate = false
          this.$message.error(err.message)
          return console.error(err);
        }
      );
      if (res && res.status == "200") {
        this.btnstate = false
        this.$message.success(res.data.message);
        this.dialogVisible = false;
        this.get_listOfResearchReports(true);
        this.roleHeadgear1 = "";
        this.roleHeadgear2 = "";
      } else {
        this.$message.error(res.data.message);
        this.btnstate = false
      }
      this.btnstate = false
    },
    // 刪除文章
    async del_deleteResearchReport(id) {
      try {
        await this.$confirm("是否继续执行操作？", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        });
        const res = await deleteResearchReport(id).catch((err) => {
          return console.error(err);
        });

        if (res && res.status == "200") {
          this.$message.success(res.data.message);
          this.dialogVisible = false;
          this.get_listOfResearchReports();
        } else {
          this.$message.error(res.data.message);
        }
      } catch (error) {
        // 用户点击取消或关闭对话框
        console.error(error);
      }
    },
    // 关闭弹窗时
    handleClose() {
      this.addform = {
        status: 0,
        body_html: "",
        title: "",
        add_time: "",
        stock_code: "",
        is_public: 0,
        heating: 0,
        category_id: null,
        subtitle: "",
        introduction: "",
        sort: "",
        is_navi_menu: 0
      };
      // this.html = ''
      this.isVisible = true;
      this.$refs.fileInput1.value = null;
      this.$refs.fileInput2.value = null;
      this.roleHeadgear1 = "";
      this.roleHeadgear2 = "";
      this.thumbnailPreview = require("@/assets/sctpmr.jpg");
      this.largeImagePreview = require("@/assets/sctpmr.jpg");
    },
    handleClosetable() { },
    // 分页
    current_change(currentPage) {
      this.currentPage = currentPage;
      this.get_listOfResearchReports();
    },
    // 重置
    resetForm() {
      this.form = {
        title_ja: "",
        title_ko: "",
        title_en: "",
        title_zh_tw: "",
        title_zh_cn: "",
      };
      this.currentPage = 1;
      this.get_listOfResearchReports();
    },
    // 编辑打开时
    tableEditing(row) {
      this.addform.category_id = "";
      this.isVisible = false;
      this.titles = "编辑";
      this.row = row;
      this.dialogVisible = true;
      this.selectedLanguage = "content_text_zh_tw";

      this.thumbnailPreview =
        row.img_min_zh_tw && row.img_min_zh_tw.trim()
          ? "" + row.img_min_zh_tw
          : require("@/assets/sctpmr.jpg");

      this.largeImagePreview =
        row.img_max_zh_tw && row.img_max_zh_tw.trim()
          ? "" + row.img_max_zh_tw
          : require("@/assets/sctpmr.jpg");
      this.$nextTick(() => {
        const waitForEditor = () => {
          try {
            if (this.editor) {
              // 当 this.editor 有值时执行逻辑
              console.log("Editor 已初始化，执行 setHtml");
              this.editor.setHtml(this.row.content_text_zh_tw || "");
              console.log(this.editor.setHtml, "setHtml完成，已设置内容");
            } else {
              // 如果 this.editor 为空，继续等待
              console.log(this.editor, "等待 Editor 初始化...");
              setTimeout(waitForEditor, 100); // 每隔 100ms 检查一次
            }
          } catch (error) {
            // 捕获异常，避免影响体验并继续尝试执行
            console.error("执行出错，继续等待 Editor 初始化...", error);
            setTimeout(waitForEditor, 100); // 如果发生错误，继续等待
          }
        };
        waitForEditor();
      });
      const isTrue = (value) => {
        if (
          value == null ||
          value == undefined ||
          value === "null" ||
          value === "undefined"
        ) {
          return false;
        }
        return true;
      };
      if (isTrue(row.title_zh_tw)) {
        this.addform.title = row.title_zh_tw;
      }
      if (isTrue(row.is_public)) {
        this.addform.is_public = row.is_public;
      }
      if (isTrue(row.status)) {
        this.addform.status = row.status;
      }
      if (isTrue(row.add_time)) {
        this.addform.add_time = row.add_time;
      }
      if (isTrue(row.stock_code)) {
        this.addform.stock_code = row.stock_code;
      }
      if (isTrue(row.heating)) {
        this.addform.heating = row.heating;
      }
      if (isTrue(row.subtitle_zh_tw)) {
        this.addform.subtitle = row.subtitle_zh_tw;
      }
      if (isTrue(row.category_id)) {
        this.addform.category_id = row.category_id;
      }
      if (isTrue(row.introduction_zh_tw)) {
        this.addform.introduction = row.introduction_zh_tw;
      }
      if (isTrue(row.sort)) {
        this.addform.sort = row.sort;
      }

      const val = Number(row.is_navi_menu);

      if (val == 0 || val == 1) {
        this.addform.is_navi_menu = val;
      } else if (val > 1) {
        this.addform.is_navi_menu = 1;
      }


      this.addform.id = row.research_report_id;
    },
    handleLanguageChange(value) {
      // 回调函数，在选择语言后触发
      console.log("选择的语言:", value);
      if (this.titles === "编辑") {
        // 确保 this.row 和 this.editor 已初始化并存在
        const languageMap = {
          content_text_ja: "ja",
          content_text_ko: "ko",
          content_text_en: "en",
          content_text_zh_tw: "zh_tw",
          content_text_zh_cn: "zh_cn",
        };

        // 获取语言后缀（例如：'ja'、'ko'、'en'、'zh_tw'）
        const langSuffix = languageMap[this.selectedLanguage];

        // 检查是否找到对应的语言后缀
        if (langSuffix) {
          this.addform.title = this.row[`title_${langSuffix}`];
          this.addform.subtitle = this.row[`subtitle_${langSuffix}`];

          this.addform.introduction =
            this.row[`introduction_${langSuffix}`] || "";

          console.log(
            this.row[`img_max_${langSuffix}`],
            "this.row[`img_max_${langSuffix}`]"
          );
          this.thumbnailPreview = this.row[`img_max_${langSuffix}`]
            ? "" + this.row[`img_max_${langSuffix}`]
            : require("@/assets/sctpmr.jpg");

          this.largeImagePreview = this.row[`img_min_${langSuffix}`]
            ? "" + this.row[`img_min_${langSuffix}`]
            : require("@/assets/sctpmr.jpg");

          // alert(this.row[`title_${langSuffix}`])
        }
        if (this.row && this.editor) {
          this.editor.setHtml(this.row[value] || "");
        } else {
          console.warn("`this.row` 或 `this.editor` 未初始化");
        }
      }
    },
    // 新增打开时
    addbtn() {
      this.dialogVisible = true;
      this.titles = "新增";
      this.isVisible = true;
    },
    // 富文本
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    // 组件销毁时销毁编辑器
    beforeDestroy() {
      const editor = this.editor;
      if (editor == null) return;
      editor.destroy();
    },
    onChange(editor) {
      console.log(editor, this.editor, "121212121");
    },
    onDestroyed(editor) {
      console.log("onDestroyed", editor);
    },
    onMaxLength(editor) {
      console.log("onMaxLength", editor);
    },
    onFocus(editor) {
      console.log("onFocus", editor);
    },
    onBlur(editor) {
      console.log("onBlur", editor);
    },
    customAlert(info, type) {
      window.alert(`customAlert in Vue demo\n${type}:\n${info}`);
    },
    customPaste(editor, event, callback) {
      console.log("ClipboardEvent 粘贴事件对象", event);
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 自定义插入内容
      // editor.insertText('xxx')

      // 返回 false ，阻止默认粘贴行为
      // event.preventDefault()
      // callback(false) // 返回值（注意，vue 事件的返回值，不能用 return）

      // 返回 true ，继续默认的粘贴行为
      // callback(true)
      console.log(editor, event, callback);
    },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.rtrtqw {
  width: 300px;
  height: 150px;
  object-fit: fill;
  cursor: pointer;
  border: 1px solid #ccc;
}

.fgfgas {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 99998;
}

.cvcvax {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 99999;
  max-width: 600px;
  max-height: 500px;
}

.btncaijian {
  width: 100%;
  height: 40px;
  cursor: pointer;
}

.cell {
  font-size: 12px;
  white-space: nowrap !important;
}

.el-dialog__body {
  padding: 0 10px !important;
}

.demo-table-expand {
  font-size: 0;
  margin-left: 10px;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
<style lang="less" scoped>
.DealerInfoStyle {
  width: 100%;
  padding: 0 10px;
  // background-color: aquamarine;
  height: calc(100vh - 100px);
  // border: 1px #000 solid;

  .cardAdmin {
    position: relative;
    // height: 18%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 0;

    border: #ebeef5 solid 1px;
    padding: 0 5px;
    margin-bottom: 2px;

    .formContainer {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      padding: 0;
      align-self: baseline;
      padding-bottom: 40px;
    }

    .formSearch {
      width: 25%;
      min-width: 25%;
      margin: 10px 0;
      height: 40px;
      display: flex;
      justify-content: center;
    }
  }

  .pop-up-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 0;
    align-self: baseline;
    margin: 10px 0;
    justify-content: center;
    padding-right: 15px;

    .form-options {
      width: 100%;
      min-width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }
}

.mhmz {
  padding: 0 10px;
  text-align: right;
  line-height: 40px;
  font-weight: 700;
  font-size: 15px;
}

.qpwo {
  display: flex;
  // height: 40px;
  width: 100%;
  justify-content: end;
  margin-right: 6px;
  position: relative;
}

.ttyyuu {
  display: flex;
  justify-content: center;
  width: 95%;
  margin: 8px 0;
}

.bbnnmm {
  flex: 4;
  text-align: right;
  line-height: 40px;
  font-weight: 700;
  font-size: 15px;
}

.qqaazz {
  flex: 1;
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.wweerr {
  flex: 2;
  text-align: center;
  line-height: 40px;
  font-weight: 700;
  font-size: 15px;
  width: 100%;
}

.aassdd {
  height: calc(100vh - 200px - 5vh - 54px - 120px - 40px);
  overflow-y: hidden;
}
</style>
